// 服务器配置类 (与Flutter版本同步)
class ServerConfig {
  static availableServers = [
    {
      name: 'www.uptimetime.com',
      url: 'wss://www.uptimetime.com/ws',
      description: 'www.uptimetime.com'
    },
    {
      name: 'uptimetime.com',
      url: 'wss://uptimetime.com/ws',
      description: 'uptimetime.com'
    },
    {
      name: 'www.bdtennis.com',
      url: 'wss://www.bdtennis.com/ws',
      description: 'www.bdtennis.com'
    },
    {
      name: 'bdtennis.com',
      url: 'wss://bdtennis.com/ws',
      description: 'bdtennis.com'
    }
  ];

  static getDefaultServerUrl() {
    return this.availableServers[0].url;
  }

  static getServerName(url) {
    const server = this.availableServers.find(s => s.url === url);
    return server ? server.name : url;
  }

  static getAllServers() {
    return this.availableServers;
  }
}

// 翻译服务类
class TranslationService {
  constructor(config = {}) {
    this.audioBuffer = {
      local: [],
      remote: []
    };
    this.isProcessing = false;
    this.onTranslationResult = null;
    this.onAsrResult = null;
    this._onTtsAudio = null; // 使用不同的内部属性名避免setter冲突
    this.onError = null;
    this.onSessionEnded = null;
    this.websocket = null;
    this.isConnected = false;
    this._currentSeq = null; // 当前会话序列号
    this._seqCounter = 1000; // 序列号计数器

    // Opus编码器 - 使用16kHz, 单声道, Audio应用类型, 60ms帧（与后端demo一致）
    this.opusEncoder = null;
    this.opusInitialized = false;

    // 音频帧缓冲区 - 60ms @ 16kHz = 960个样本
    this.frameBuffer = new Float32Array(960);
    this.frameIndex = 0;
    this.frameCount = 0;
    this.totalOpusBytes = 0;

    // 音频处理统计
    this.audioStats = {
      local: { frames: 0, bytes: 0, lastProcessed: 0 },
      remote: { frames: 0, bytes: 0, lastProcessed: 0 }
    };

    // 配置参数（按Flutter方式：实时发送，不缓冲）
    this.config = {
      // 移除缓冲相关配置，按Flutter方式实时发送
      websocketUrl: config.websocketUrl || ServerConfig.getDefaultServerUrl(), // 使用服务器配置的默认地址
      fromLanguage: config.fromLanguage || 'zh-CN', // 源语言
      toLanguage: config.toLanguage || 'en-US', // 目标语言
      silenceFilter: {
        enabled: false,//不开启静音检测，会导致 asr 一直不返回 isLast=true
        threshold: 0.009, // 降低阈值，让RMS=0.001左右的音频能通过
        description: '过滤静音或音量过低的音频帧，减少无效数据传输'
      },
      ...config
    };

    // 初始化 WebSocket 连接
    this.initWebSocket();

    // 延迟初始化 Opus 编码器，确保库已加载
    setTimeout(() => {
      this.initOpusEncoder();
    }, 500);
  }

  // 初始化 Opus 编码器
  async initOpusEncoder() {
    console.log('🔧 开始初始化Opus编码器...');

    // 等待Opus库加载的函数
    const waitForOpusLibrary = () => {
      return new Promise((resolve, reject) => {
        let attempts = 0;
        const maxAttempts = 30; // 最多等待30秒

        const checkLibrary = () => {
          attempts++;
          console.log(`🔍 第${attempts}次检查Opus库状态:`, {
            OpusEncoder: typeof OpusEncoder,
            OpusApplication: typeof OpusApplication,
            Module: typeof Module,
            _opus_encoder_create: typeof _opus_encoder_create
          });

          // 检查所有必需的对象
          if (typeof OpusEncoder !== 'undefined' &&
              typeof OpusApplication !== 'undefined' &&
              typeof Module !== 'undefined' &&
              typeof _opus_encoder_create !== 'undefined') {
            console.log('✅ Opus库已完全加载！');
            resolve();
            return;
          }

          if (attempts >= maxAttempts) {
            reject(new Error('Opus库加载超时'));
            return;
          }

          // 等待1秒后重试
          setTimeout(checkLibrary, 1000);
        };

        checkLibrary();
      });
    };

    try {
      // 等待Opus库完全加载
      await waitForOpusLibrary();

      console.log('🔧 创建Opus编码器: 16kHz, 单声道, Audio应用, 60ms帧');
      // 16kHz采样率，单声道，Audio应用，60ms帧长度（与后端demo一致）
      this.opusEncoder = new OpusEncoder(16000, 1, OpusApplication.Audio, 60);
      this.opusInitialized = true;
      console.log('✅ Opus编码器初始化成功: 16kHz, 单声道, Audio模式, 60ms帧');

      // 测试编码器
      const testData = new Float32Array(960); // 60ms @ 16kHz
      testData.fill(0.1); // 填充测试数据
      const testPackets = this.opusEncoder.encode_float(testData);
      console.log('🧪 Opus编码器测试成功，生成', testPackets.length, '个数据包');

    } catch (error) {
      console.error('❌ Opus编码器初始化失败:', error);
      console.error('❌ 错误详情:', error.stack);
      this.opusInitialized = false;

      // 5秒后重试
      setTimeout(() => {
        console.log('🔄 重试初始化Opus编码器...');
        this.initOpusEncoder();
      }, 5000);
    }
  }

  // 初始化 WebSocket 连接
  initWebSocket() {
    try {
      console.log('🔗 正在连接到翻译服务:', this.config.websocketUrl);
      this.websocket = new WebSocket(this.config.websocketUrl);

      this.websocket.onopen = () => {
        console.log('✅ 翻译服务 WebSocket 连接成功:', this.config.websocketUrl);
        this.isConnected = true;

        // 发送配置信息
        this.sendConfig();
      };

      this.websocket.onmessage = (event) => {
        try {
          // 添加详细的调试信息
          console.log('📨 收到WebSocket消息:', event.data);

          const data = JSON.parse(event.data);
          console.log('📨 解析后的消息:', data);

          this.handleWebSocketMessage(data);
        } catch (error) {
          console.error('解析 WebSocket 消息失败:', error);
          console.error('原始消息内容:', event.data);
        }
      };

      this.websocket.onclose = (event) => {
        console.log('❌ 翻译服务 WebSocket 连接关闭:', {
          code: event.code,
          reason: event.reason,
          wasClean: event.wasClean
        });
        this.isConnected = false;

        // 只有在非正常关闭时才重连
        if (!event.wasClean) {
          setTimeout(() => {
            if (!this.isConnected) {
              console.log('🔄 尝试重连翻译服务...');
              this.initWebSocket();
            }
          }, 3000);
        }
      };

      this.websocket.onerror = (error) => {
        console.error('❌ 翻译服务 WebSocket 错误:', error);
        console.error('连接URL:', this.config.websocketUrl);
        this.isConnected = false;
      };

    } catch (error) {
      console.error('❌ 初始化翻译服务 WebSocket 失败:', error);
    }
  }

  // 开始翻译会话（完全基于Flutter版本）
  async startTranslation(fromLanguage = null, toLanguage = null) {
    if (!this.isConnected) {
      console.warn('WebSocket未连接，无法开始翻译');
      return;
    }

    // 使用传入的语言或配置中的语言
    const sourceLanguage = fromLanguage || this.config.fromLanguage;
    const targetLanguage = toLanguage || this.config.toLanguage;

    // 生成序列号（与Flutter版本一致的格式）
    this._currentSeq = this._generateSequence(sourceLanguage, targetLanguage);

    // 构造开始报文（与Flutter版本完全一致）
    const startMessage = {
      'businessType': 'ENTITY_TRANS',
      'auto': 1,
      'to': targetLanguage,
      'detectMode': 1, //  自动检测语言
      'mockType': 1,
      'sound': 2,
      'tsEnable': 1,
      'action': 'SATS',
      'from': sourceLanguage,
      'flag': 'start',
      'ttsFormat': 'mp3',
      'ttsEnable': 0, // 关闭TTS语音合成
      'ttsGender': 'female',
      'seq': this._currentSeq,
      'asrFormat': 'rawopus', // 使用Opus编码格式
      'flow': 1,
    };

    try {
      this.websocket.send(JSON.stringify(startMessage));
      console.log('📤 发送开始报文:', `from=${sourceLanguage}, to=${targetLanguage}, seq=${this._currentSeq}`);
      console.log('📤 开始报文详细内容:', JSON.stringify(startMessage, null, 2));

      // 重置音频缓冲区（开始新会话时清理）
      this.frameIndex = 0;
      this.frameCount = 0;
      this.totalOpusBytes = 0;
      console.log('🔄 已重置音频缓冲区，准备60ms帧缓冲');

      // 等待一小段时间让服务器处理开始报文
      await new Promise(resolve => setTimeout(resolve, 100));
      console.log('✅ 翻译会话已开始，准备接收音频数据');

    } catch (error) {
      console.error('❌ 发送开始报文失败:', error);
      throw error;
    }
  }

  // 生成序列号（与Flutter版本一致）
  _generateSequence(fromLanguage, targetLanguage) {
    const randomStr = Array.from({length: 32}, () =>
      Math.floor(Math.random() * 16).toString(16).toUpperCase()).join('');
    const timestamp = Date.now();

    return `${fromLanguage}|${targetLanguage}|${randomStr}|${timestamp}`;
  }

  // 发送配置信息到后端（废弃的方法，保持兼容性）
  sendConfig() {
    // 自动开始翻译会话
    this.startTranslation();
  }

  // 处理 WebSocket 消息（完全基于Flutter版本）
  handleWebSocketMessage(data) {
    console.log('🔍 处理消息:', data);
    console.log('🔍 消息详细信息:', JSON.stringify(data, null, 2));

    const step = data.step;
    const code = data.code;
    const asrSid = data.asrSid;

    // 处理结束会话响应 (code: 2025)
    if (code === 2025) {
      const msg = data.msg || '会话结束';
      console.log('✅ 服务器确认会话结束:', msg);
      // 清理当前序列号
      this._currentSeq = null;
      // 通知上层应用会话已结束
      if (this.onSessionEnded) {
        this.onSessionEnded(msg);
      }
      return;
    }

    if (code !== 0) {
      const errorMsg = data.msg || '未知错误';
      console.error('❌ 服务器错误:', `${errorMsg} (code: ${code})`);

      // 如果是会话状态错误(504)，尝试重新开始会话
      if (code === 504 && data.msg === '会话状态错误') {
        console.log('🔄 检测到会话状态错误，尝试重新开始会话...');
        setTimeout(() => {
          this.startTranslation();
        }, 1000);
      }

      if (this.onError) {
        this.onError(`服务器错误: ${errorMsg}`);
      }
      return;
    }

    // 处理成功响应
    switch (step) {
      case 'ASR':
        this._handleAsrResponse(data);
        break;
      case 'TS':
        this._handleTranslationResponse(data);
        break;
      case 'TTS':
        this._handleTtsResponse(data);
        break;
      default:
        console.log('⚠️ 未知步骤:', step);
    }
  }

  // 处理ASR响应（与Flutter版本一致）
  _handleAsrResponse(data) {
    const text = data.text;
    const asrSid = data.asrSid;
    const isLast = data.isLast;
    // 智能提取检测到的语言
    let detectedLanguage = data.detected_language;

    // 如果detected_language为空，尝试从from字段提取第一个语言
    if (!detectedLanguage && data.from) {
      // from字段可能是 "zh-CN,en-US" 格式，提取第一个语言
      detectedLanguage = data.from.split(',')[0].trim();
    }

    console.log('🔍 语言检测详情:', {
      raw_detected_language: data.detected_language,
      raw_from: data.from,
      final_detectedLanguage: detectedLanguage
    });

    if (text && asrSid) {
      console.log('🎤 ASR识别:', `${text} (isLast: ${isLast}, lang: ${detectedLanguage})`);
      if (this.onAsrResult) {
        this.onAsrResult(text, asrSid, isLast || false, detectedLanguage);
      }
    }
  }

  // 处理翻译结果（与Flutter版本一致）
  _handleTranslationResponse(data) {
    const text = data.text;
    const asrSid = data.asrSid;
    const sourceLanguage = data.from;
    const targetLanguage = data.to;

    console.log('🔤 翻译结果:', `text: ${text}, sourceLanguage: ${sourceLanguage}, targetLanguage: ${targetLanguage}`);

    if (text && asrSid) {
      console.log('🔤 翻译结果:', text);
      if (this.onTranslationResult) {
        this.onTranslationResult(text, asrSid, sourceLanguage || '', targetLanguage || '');
      }
    }
  }

  // 处理TTS结果（与Flutter版本一致）
  _handleTtsResponse(data) {
    const url = data.url;
    const asrSid = data.asrSid;

    if (url && asrSid) {
      console.log('🔊 TTS音频:', url);
      if (this._onTtsAudio) {
        this._onTtsAudio(url, asrSid);
      }
    }
  }

  // 处理音频数据（按Flutter方式：小块实时发送）
  async processAudioData({ type, data, sampleRate }) {
    try {
      // 检查 WebSocket 连接
      if (!this.isConnected) {
        return;
      }

      // 检查数据有效性（与Flutter一致）
      if (!data || data.length < 32) { // 32个Float32样本 ≈ 64字节PCM
        return; // 数据太少，认为无效
      }

      // 添加音频类型处理日志
      if (Math.random() < 0.005) { // 0.5%概率输出日志
        console.log(`🎵 处理${type}音频数据: ${data.length}样本, ${sampleRate}Hz`);
      }

      // 将音频数据分割为小块，与Flutter的320字节（160样本）一致
      const chunkSize = 160; // 160个Float32样本 = 320字节PCM = 10ms音频

      for (let i = 0; i < data.length; i += chunkSize) {
        const chunk = data.slice(i, i + chunkSize);

        // 确保块大小足够（避免发送过小的尾部数据）
        if (chunk.length < 32) {
          continue; // 跳过过小的块
        }

        // 启用静音过滤，过滤背景噪音和无意义的声音
        // if (this.config.silenceFilter.enabled && this.isSilence(chunk)) {
        //   continue; // 跳过静音或音频过低的音频帧
        // }

        // 发送小块音频数据（与Flutter一致）
        await this.sendAudioToWebSocket(type, chunk, sampleRate);
      }

    } catch (error) {
      console.error('处理音频数据失败:', error);
    }
  }

  // 通过 WebSocket 发送音频数据（使用Opus编码）
  async sendAudioToWebSocket(type, audioData, sampleRate) {
    try {
      if (!this.isConnected || this._currentSeq === null) {
        console.warn('WebSocket未连接或会话未开始，跳过音频数据发送');
        return;
      }

      if (!this.opusInitialized || !this.opusEncoder) {
        if (Math.random() < 0.02) { // 2%概率输出警告，避免刷屏
          console.warn('⚠️ Opus编码器未初始化，跳过音频数据发送', {
            opusInitialized: this.opusInitialized,
            opusEncoder: !!this.opusEncoder,
            OpusEncoder: typeof OpusEncoder,
            OpusApplication: typeof OpusApplication
          });
        }
        return;
      }

      // 确保音频数据为16kHz（Opus编码器要求）
      let processedAudio = audioData;
      if (sampleRate !== 16000) {
        processedAudio = this.resampleTo16kHz(audioData, sampleRate);
        if (Math.random() < 0.05) { // 5%的概率输出重采样信息
          console.log(`🔄 音频重采样: ${sampleRate}Hz -> 16000Hz, 样本数: ${audioData.length} -> ${processedAudio.length}`);
        }
      }

            // 使用60ms帧缓冲机制（与后端demo一致）
      this.bufferAudioForOpusEncoding(processedAudio, type);

    } catch (error) {
      console.error(`❌ 发送${type}音频失败:`, error);
    }
  }

  // 音频帧缓冲机制 - 与后端demo完全一致
  bufferAudioForOpusEncoding(audioData, type) {
    try {
      // 60ms @ 16kHz = 960个样本
      const FRAME_SIZE = 960;

      // 将输入数据添加到帧缓冲区
      for (let i = 0; i < audioData.length; i++) {
        if (this.frameIndex < FRAME_SIZE) {
          this.frameBuffer[this.frameIndex++] = audioData[i];

          // 当收集满60ms数据时，编码并发送
          if (this.frameIndex === FRAME_SIZE) {
            try {
              // 直接将Float32Array传递给编码函数（与demo一致）
              const opusPackets = this.opusEncoder.encode_float(this.frameBuffer);

              if (opusPackets && opusPackets.length > 0) {
                const opusFrame = new Uint8Array(opusPackets[0]); // 返回第一个完整的Opus帧
                this.websocket.send(opusFrame);

                this.frameCount++;
                this.totalOpusBytes += opusFrame.length;

                // 更新音频统计
                if (this.audioStats[type]) {
                  this.audioStats[type].frames++;
                  this.audioStats[type].bytes += opusFrame.length;
                  this.audioStats[type].lastProcessed = Date.now();
                }

                // 每10帧记录一次（与demo一致）
                if (this.frameCount % 10 === 0) {
                  const avgSize = Math.round(this.totalOpusBytes / this.frameCount);
                  const compressionRatio = Math.round((FRAME_SIZE * 2) / avgSize * 100) / 100;
                  console.log(`📡 Raw Opus帧 #${this.frameCount}: 60ms编码完成 (${opusFrame.length}字节, 平均${avgSize}字节, 压缩比${compressionRatio}:1)`);
                }
              }
            } catch (encodeError) {
              console.error(`❌ Opus编码失败: ${encodeError.message}`);
              // 如果编码失败，重新初始化编码器
              this.opusInitialized = false;
              setTimeout(() => this.initOpusEncoder(), 1000);
            }

            // 重置帧缓冲区（关键步骤）
            this.frameIndex = 0;
          }
        }
      }
    } catch (error) {
      console.error(`❌ 音频缓冲处理失败:`, error);
    }
  }

  // 重采样到16kHz（简单线性插值）
  resampleTo16kHz(audioData, originalSampleRate) {
    if (originalSampleRate === 16000) return audioData;

    const ratio = originalSampleRate / 16000;
    const newLength = Math.floor(audioData.length / ratio);
    const resampled = new Float32Array(newLength);

    for (let i = 0; i < newLength; i++) {
      const originalIndex = i * ratio;
      const index = Math.floor(originalIndex);
      const fraction = originalIndex - index;

      if (index + 1 < audioData.length) {
        // 线性插值
        resampled[i] = audioData[index] * (1 - fraction) + audioData[index + 1] * fraction;
      } else {
        resampled[i] = audioData[index] || 0;
      }
    }

    return resampled;
  }

  // 将Float32Array转换为16位PCM数据（与Flutter版本保持一致）
  float32ToPCM16(float32Array) {
    const buffer = new ArrayBuffer(float32Array.length * 2);
    const view = new DataView(buffer);

    for (let i = 0; i < float32Array.length; i++) {
      // 将float32值（-1.0到1.0）转换为16位整数（-32768到32767）
      const sample = Math.max(-1, Math.min(1, float32Array[i]));
      const intValue = Math.round(sample * 32767);
      view.setInt16(i * 2, intValue, true); // 小端序
    }

    return new Uint8Array(buffer);
  }

  // 结束翻译会话（与Flutter版本一致）
  async endTranslation() {
    if (!this.isConnected || this._currentSeq === null) return;

    const endMessage = {
      'seq': this._currentSeq,
      'action': 'SATS',
      'ttsFormat': 'mp3',
      'flag': 'end',
    };

    try {
      this.websocket.send(JSON.stringify(endMessage));
      console.log('📤 发送结束报文:', `seq: ${this._currentSeq}`);
      this._currentSeq = null;
    } catch (error) {
      console.error('❌ 发送结束报文失败:', error);
    }
  }

  // 检查是否为静音
  isSilence(audioData) {
    if (!audioData || audioData.length < 32) {
      return true; // 数据太少，认为是静音
    }

    // 计算音频能量（RMS - 均方根）
    let sum = 0.0;
    const sampleCount = Math.min(audioData.length, 500); // 限制采样数量以提高性能

    // 采样检查，避免计算所有数据点
    for (let i = 0; i < sampleCount; i++) {
      const sample = audioData[i];
      sum += sample * sample;
    }

    if (sampleCount === 0) return true;

    // 计算RMS（均方根）
    const rms = Math.sqrt(sum / sampleCount);

    // 使用适合Float32范围的阈值
    const silenceThreshold = this.config.silenceFilter.threshold; // 0.01

    const isValid = rms > silenceThreshold;

    // 偶尔打印调试信息（避免日志刷屏）- 每100次采样打印一次
    if (Math.random() < 0.01) {
      console.log(`🎵 音频有效性检查: RMS=${rms.toFixed(4)}, threshold=${silenceThreshold}, valid=${isValid}`);
    }

    return !isValid; // 返回是否为静音
  }

  // 将 Float32Array 转换为 WAV 格式
  audioDataToWav(audioData, sampleRate) {
    const length = audioData.length;
    const buffer = new ArrayBuffer(44 + length * 2);
    const view = new DataView(buffer);

    // WAV 文件头
    const writeString = (offset, string) => {
      for (let i = 0; i < string.length; i++) {
        view.setUint8(offset + i, string.charCodeAt(i));
      }
    };

    writeString(0, 'RIFF');
    view.setUint32(4, 36 + length * 2, true);
    writeString(8, 'WAVE');
    writeString(12, 'fmt ');
    view.setUint32(16, 16, true);
    view.setUint16(20, 1, true);
    view.setUint16(22, 1, true);
    view.setUint32(24, sampleRate, true);
    view.setUint32(28, sampleRate * 2, true);
    view.setUint16(32, 2, true);
    view.setUint16(34, 16, true);
    writeString(36, 'data');
    view.setUint32(40, length * 2, true);

    // 转换音频数据
    let offset = 44;
    for (let i = 0; i < length; i++) {
      const sample = Math.max(-1, Math.min(1, audioData[i]));
      view.setInt16(offset, sample * 0x7FFF, true);
      offset += 2;
    }

    return buffer;
  }

  // ArrayBuffer 转 Base64
  arrayBufferToBase64(buffer) {
    const bytes = new Uint8Array(buffer);
    let binary = '';
    for (let i = 0; i < bytes.byteLength; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
  }

  // 设置翻译结果回调（与Flutter版本一致的接口）
  setTranslationCallback(callback) {
    this.onTranslationResult = callback;
  }

  // 设置ASR结果回调
  setAsrCallback(callback) {
    this.onAsrResult = callback;
  }

  // 设置TTS音频回调
  setTtsCallback(callback) {
    this._onTtsAudio = callback;
  }

  // 兼容旧接口
  set onTranslation(callback) {
    this.onTranslationResult = callback;
  }

  set onAsr(callback) {
    this.onAsrResult = callback;
  }

  set onTtsAudio(callback) {
    this._onTtsAudio = callback;
  }

  // 更新配置
  updateConfig(newConfig) {
    this.config = { ...this.config, ...newConfig };

    // 如果连接已建立，重新发送配置
    if (this.isConnected) {
      this.sendConfig();
    }
  }

  // 设置服务器URL
  setServerUrl(serverUrl) {
    if (this.isConnected) {
      console.warn('WebSocket已连接，正在断开现有连接...');
      this.websocket.close();
    }

    this.config.websocketUrl = serverUrl;
    console.log(`🌐 服务器URL已更改为: ${serverUrl}`);

    // 重新初始化WebSocket连接
    this.initWebSocket();
  }

  // 获取当前服务器URL
  getServerUrl() {
    return this.config.websocketUrl;
  }

  // 获取当前服务器名称
  getServerName() {
    return ServerConfig.getServerName(this.config.websocketUrl);
  }

  // 获取所有可用服务器
  getAvailableServers() {
    return ServerConfig.getAllServers();
  }

  // 获取连接状态
  getConnectionStatus() {
    const wsState = this.websocket ? this.websocket.readyState : null;
    const wsStateText = wsState === WebSocket.CONNECTING ? 'CONNECTING' :
                       wsState === WebSocket.OPEN ? 'OPEN' :
                       wsState === WebSocket.CLOSING ? 'CLOSING' :
                       wsState === WebSocket.CLOSED ? 'CLOSED' : 'UNKNOWN';

    return {
      isConnected: this.isConnected,
      websocketState: wsState,
      websocketStateText: wsStateText,
      serverUrl: this.config.websocketUrl,
      serverName: this.getServerName(),
      currentSeq: this._currentSeq,
      hasActiveSession: this._currentSeq !== null
    };
  }

  // 获取音频处理配置信息
  getAudioConfig() {
    return {
      mode: 'web_audio_api_opus',
      description: '使用Web Audio API获取音频流，Opus编码实时传输',
      sampleRate: '16kHz (Opus)',
      channel: 'Mono',
              encoding: {
        format: 'rawopus',
        frameDuration: '60ms',
        application: 'Audio',
        initialized: this.opusInitialized
      },
      silenceFilter: {
        enabled: this.config.silenceFilter.enabled,
        threshold: this.config.silenceFilter.threshold,
        description: this.config.silenceFilter.description
      },
      apis: [
        'AudioContext',
        'createScriptProcessor',
        'createMediaStreamSource',
        'getChannelData',
        'OpusEncoder'
      ],
      bufferConfig: {
        bufferDuration: this.config.bufferDuration,
        maxBufferSize: this.config.maxBufferSize,
        description: '音频缓冲和批处理设置'
      }
    };
  }

  // 获取音频统计信息
  getAudioStats() {
    return {
      local: {
        frames: this.audioStats.local.frames,
        bytes: this.audioStats.local.bytes,
        lastProcessed: this.audioStats.local.lastProcessed,
        timeSinceLastProcessed: this.audioStats.local.lastProcessed ? Date.now() - this.audioStats.local.lastProcessed : null
      },
      remote: {
        frames: this.audioStats.remote.frames,
        bytes: this.audioStats.remote.bytes,
        lastProcessed: this.audioStats.remote.lastProcessed,
        timeSinceLastProcessed: this.audioStats.remote.lastProcessed ? Date.now() - this.audioStats.remote.lastProcessed : null
      }
    };
  }

  // 获取缓冲区状态
  getBufferStatus() {
    return {
      local: {
        length: this.audioBuffer.local.length,
        duration: this.audioBuffer.local.length / 48000 // 假设 48kHz 采样率
      },
      remote: {
        length: this.audioBuffer.remote.length,
        duration: this.audioBuffer.remote.length / 48000
      },
      isProcessing: this.isProcessing,
      isConnected: this.isConnected,
      silenceFilter: {
        enabled: this.config.silenceFilter.enabled,
        threshold: this.config.silenceFilter.threshold
      }
    };
  }

  // 清理缓存
  clearBuffer(type = null) {
    if (type) {
      this.audioBuffer[type] = [];
    } else {
      this.audioBuffer = { local: [], remote: [] };
    }
    this.isProcessing = false;
  }

  // 销毁服务（与Flutter版本一致）
  destroy() {
    // 结束当前会话
    if (this._currentSeq !== null) {
      this.endTranslation();
    }

    // 清理Opus编码器
    if (this.opusEncoder) {
      try {
        this.opusEncoder.destroy();
        console.log('🧹 Opus编码器已清理');
      } catch (error) {
        console.warn('清理Opus编码器时出错:', error);
      }
      this.opusEncoder = null;
    }
    this.opusInitialized = false;

    // 重置音频缓冲区
    this.frameIndex = 0;
    this.frameCount = 0;
    this.totalOpusBytes = 0;

    this.clearBuffer();
    this.onTranslationResult = null;
    this.onAsrResult = null;
    this._onTtsAudio = null;

    if (this.websocket) {
      this.websocket.close();
      this.websocket = null;
    }

    this.isConnected = false;
    this._currentSeq = null;
  }
}

// 导出类
window.ServerConfig = ServerConfig;
window.TranslationService = TranslationService;
